package paper.http;

import java.net.URL;
import java.io.*;

public class ClassReLoader extends ClassLoader {
    public ClassReLoader() {
        super();
    }
    
    public Class loadClass(String x, boolean r) throws ClassNotFoundException {
        if (!x.startsWith("paper") ||
            x.startsWith("paper.db") ||
            x.equals("paper.pdf.Extractor")) {
            return super.loadClass(x,r);
        }
        Class c = findLoadedClass(x);
        if (c == null) {
            try {
                URL classResource = getResource(x.replace('.', '/') + ".class");
                if (classResource == null) {
                    System.out.println("Class not found in " + x );
                } else {
                    InputStream input = classResource.openStream();
                    System.out.println("Loading: " + x);
                    byte[] data = new byte[input.available()];
                    int off = 0, len = data.length, read;
                    while ((read = input.read(data, off, len)) > 0) {
                        off += read;
                        len -= read;
                    }
                    
                    c = defineClass(x, data, 0, data.length);
                }
            } catch (Exception e) {
                System.out.println("Findclass: " + e);
            }
//            System.out.println("Findclass: " + x + " : " + c);
            if (c == null) {
                c = super.loadClass(x,r);
//                System.out.println("superFindloadedclass: " + x + " : " + c);
            }
        }
        if (r) {
            resolveClass(c);
        }
        return c;
    }
}
